package com.linxz.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import Decoder.BASE64Encoder;

/**
 * @author Linxz
 * 创建日期：2019年02月20日 20:00
 * version：1.0.0
 * 描述：
 */
public class FileUtil {


    private static final String SDPATH = Environment.getExternalStorageDirectory() + "/";
    public static final String FILEPAHT=SDPATH+"yzyl/images/";
    public final static String ALBUM_PATH=Environment.getExternalStorageDirectory()+File.separator+"yzyl"+File.separator;
    private final static String Second_PATH=ALBUM_PATH+"images"+File.separator;

    public static FileUtil getFileUtil(){
        return Builder.INSTANCE;
    }

    private static class Builder{
        private static FileUtil INSTANCE=new FileUtil();
    }


    public FileUtil(){
        //创建文件夹
        File dirFirstFile=new File(ALBUM_PATH);
        if(!dirFirstFile.exists()){
            dirFirstFile.mkdir();
        }
        File dirSecondFile=new File(Second_PATH);
        if(!dirSecondFile.exists()){
            dirSecondFile.mkdir();
        }
    }

    public void init(){}


    /**
     * 读取raw目录中的文件,并返回为字符串
     */
    public static String getRawFile(Context context, int id) {
        final InputStream is = context.getResources().openRawResource(id);
        final BufferedInputStream bis = new BufferedInputStream(is);
        final InputStreamReader isr = new InputStreamReader(bis);
        final BufferedReader br = new BufferedReader(isr);
        final StringBuilder stringBuilder = new StringBuilder();
        String str;
        try {
            while ((str = br.readLine()) != null) {
                stringBuilder.append(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
                isr.close();
                bis.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stringBuilder.toString();
    }


    private String sdpath;
    /**
     * 判断文件是否存在
     *
     * @param fileName
     * @return
     */
    public boolean isFileExist(String fileName) {
        File file = new File(sdpath + fileName);
        return file.exists();
    }

    public File write2SDFromInput(String path, String fileName, InputStream input) {
        File file = null;
        OutputStream output = null;

        try {
            createDir(path);
            try {
                file = createSDFile(path + fileName);
            } catch (Exception ex) {
                //ex.printStackTrace();
                file = new File(path + "/" + fileName);
                //file.mkdir();
                String dir = file.getParent();
                new File(dir).mkdirs();
                //file.mkdirs();
                file.createNewFile();
            }

            output = new FileOutputStream(file);
            byte[] buffer = new byte[4 * 1024];
            int num = 0;
            while ((num = input.read(buffer)) != -1) {
                output.write(buffer, 0, num);
            }
            output.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) {
                    output.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 在SD卡上创建目录
     *
     * @param dirName 目录名字
     * @return 文件目录
     */
    public File createDir(String dirName) {
        File dir = new File(sdpath + dirName);
        dir.mkdir();
        return dir;
    }

    /**
     * 在SD卡上创建文件
     *
     * @param fileName
     * @return
     * @throws IOException
     */
    public File createSDFile(String fileName) throws IOException {
        File file = new File(sdpath + fileName);
        file.createNewFile();
        return file;
    }


    /**
     * 将图片转为Base64
     * **/
//    public static String getBase64FromFilePath(String path){
//        InputStream in = null;
//        byte[] data = null;
//        // 读取图片字节数组
//        try {
//            in = new FileInputStream(path);
//            data = new byte[in.available()];
//            in.read(data);
//            in.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        // 对字节数组Base64编码
//        // 返回Base64编码过的字节数组字符串
//        String base64="data:image/jpeg;base64,"+ Base64.encodeToString(data,Base64.NO_WRAP);
////        base64=base64.replaceAll("\\n","");
////        base64=base64.replaceAll(" ","+");
//        return base64;
//    }

    public static String getBase64FromFilePath(String path){
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(path);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        String base64=encoder.encode(data);
        base64="data:image/jpeg;base64,"+base64;
        return base64;
    }



    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }


    public int saveBitmapToPhone(Bitmap newBitmap){
        try {
            File folder = new File(ALBUM_PATH);
            if(!folder.exists()){
                folder.mkdir();
            }
            String name="QRCode"+System.currentTimeMillis();
            File file = new File(ALBUM_PATH + name + ".jpg");
            if(file.exists()){
                file.delete();
            }
            if(!file.exists()){
                file.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(file);
            newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }
}
